package com.cynteka.cyfoman.core.collection;

/**
 * User: Sergey
 * Date: 29.07.11
 * Time: 17:24
 */
public class BaseSQLGenerator implements ISQLGenerator {

    @Override
    public String generateSimpleSelect(String tableName) {
        return String.format("select * from %1$s", tableName);
    }

    @Override
    public String generateSelectByFieldName(String tableName, String fieldName) {
        return String.format("select * from %1$s where %2$s = ?", tableName, fieldName);
    }

    @Override
    public String generateSelectByFieldNameIsNull(String tableName, String fieldName) {
        return String.format("select * from %1$s where %2$s is null", tableName, fieldName);
    }

    @Override
    public String generateSelectByChildId(String tableName, String fieldIdName, String fieldReferenceName) {
        return String.format("select t1.* from %1$s t1 join %1$s t2 on t1.%2$s = t2.%3$s where t2.%2$s = ?", tableName, fieldIdName, fieldReferenceName);
    }

    @Override
    public String generateSelectByChildId(String sourceTableName, String sourceIdFieldName, String destinationTableName, String destinationIdFieldName, String referenceFieldName) {
        return String.format("select t1.* from %1$s t1 join %2$s t2 on t1.%3$s = t2.%4$s where t2.%5$s = ?", sourceTableName, destinationTableName, sourceIdFieldName, referenceFieldName, destinationIdFieldName);
    }

    @Override
    public String generateSelectThroughCrossTable(String crossTableName, String sourceCrossFieldName, String destinationTableName, String destinationCrossFieldName, String destinationIdFieldName) {
        return String.format("select t2.* " +
                "from %1$s t1 join %3$s t2 on t1.%4$s = t2.%5$s " +
                "where t1.%2$s = ?",
                crossTableName, sourceCrossFieldName, destinationTableName, destinationCrossFieldName, destinationIdFieldName);
    }

    @Override
    public String generateSelectReferenceTable(String destinationTable, String referenceFieldName) {
        return String.format("select * " +
                "from %1$s " +
                "where %2$s = ?", destinationTable, referenceFieldName);
    }
}
